﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Infrastructure.Coding
{
    public class Extensions<T> where T:new()
    {
            /// <summary>
            /// Find a T entity in an IList. 
            /// </summary>
            /// <param name="list"></param>
            /// <param name="predicate"></param>
            /// <returns>null if not found, the object if found.</returns>
            public static T FindInList(IList<T> list , Predicate<T> predicate)
            {
                if (list == null) return default(T);
                for (int i = 0; i < list.Count; i++)
                {
                    if (predicate(list[i]))
                        return list[i];
                }
                return default(T);
            }

            public static int FindIndexInList(IList<T> list, Predicate<T> predicate)
            {
                if (list == null) return -1;
                for (int i = 0; i < list.Count; i++)
                {
                    if (predicate(list[i]))
                        return i;
                }
                return -1;
            }

            public static T FindMaxInList(IList<T> list, Comparison<T> comparer)
            {
                if (list == null) return default(T);
                if (list.Count == 0) return default(T);

                T max = list[0];
                for (int i = 0; i < list.Count; i++)
                {
                    if (comparer(list[i], max) > 0)
                        max = list[i];
                }
                return max;
            }
        }
    }
